<template>
  <edit-layout ref="layout" :page="page" :form="form" @invoke="invoke">
    <el-form
      ref="form"
      :model="form"
      :size="page.settings.formSize"
      :label-width="page.settings.labelWidth"
    >
      <div v-if="form.id == null">
        <el-row>
          <el-col :span="8">
            <el-form-item label="绑定运输单号" prop="toOrderId" :rules="page.rules.def">
              <form-remote-select
                v-model="form.toOrderId"
                :url="$http.conf.api.get('wms').url+'/api/logistics/order/map/0/0'"
                @change="toOrderNoChange"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item label="绑定回头运输单" prop="returnOrderId">
              <form-remote-select
                v-model="form.returnOrderId"
                :url="$http.conf.api.get('wms').url+'/api/logistics/order/map/1'"
              />
            </el-form-item>
          </el-col> -->
        </el-row>
      </div>
      <div v-else>
        <div class="bb20 w120">
          <el-form-item label="订单状态:" prop="status">
            <el-steps v-if="form.status!=-1" :active="form.status" finish-status="success" :space="200">
              <el-step
                v-for="item in constants.costSuccessStatus.values()"
                :key="item.value"
                :title="item.label"
                :value="item.value"
              />
            </el-steps>
          </el-form-item>
        </div>
        <el-divider content-position="left">基本信息</el-divider>
        <el-row class="row-bg">
          <el-col :span="8">
            <el-form-item label="订单号：">
              <label>{{ form.no }}</label>
              <el-tag :type="orderStatus.type" size="mini" effect="plain">{{ orderStatus.label }}</el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="运单号：">
              <label>{{ form.toOrderNo }}</label>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item v-if="form.status==0" label="回头运输单" prop="returnOrderId">
              <form-remote-select
                v-model="form.returnOrderId"
                :url="$http.conf.api.get('wms').url+'/api/logistics/order/map/1/'+form.empId"
                :disabled="form.status==0?false:true"
                name="selectReturnOrder"
                @change="bindchaneReturnOrder"
              />
            </el-form-item>
            <el-form-item v-if="form.status!=0 && form.returnOrderNo" label="回头运输单" prop="returnOrderNo">
              <label>{{ form.returnOrderNo }}</label>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="纸厂单号：">
              <label>{{ form.toOrderInfo.pageNo }}</label>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="上次里程(km)：">
              <label>{{ form.preMileage }} </label>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item v-if="form.status==0" label="本次里程数(km):" prop="nowMileage" :rules="page.rules.def">
              <el-input-number
                v-model="form.nowMileage"
                controls-position="right"
                :precision="2"
                :disabled="form.status==0?false:true"
                :min="0"
                @change="inputNowMileage"
              />
            </el-form-item>
            <el-form-item v-else label="本次里程数(km):" prop="nowMileage">
              <label>{{ form.nowMileage }}</label>
            </el-form-item>
          </el-col>
          <el-col v-if="form.aveConsumption" :span="8">
            <el-form-item label="油耗(L/km):" prop="aveConsumption">
              <label>{{ form.aveConsumption }}</label>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item v-if="form.status==0" label="加油升数(L):" prop="fuelConsumption" :rules="page.rules.def">
              <el-input-number
                v-model="form.fuelConsumption"
                controls-position="right"
                :precision="2"
                :disabled="form.status==0?false:true"
                :min="0"
              />
            </el-form-item>
            <el-form-item v-else label="加油升数(L):" prop="fuelConsumption">
              <label>{{ form.fuelConsumption }}</label>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item v-if="form.status==0" label="燃油单价(元):" prop="fuelPrice" :rules="page.rules.def">
              <el-input-number
                v-model="form.fuelPrice"
                controls-position="right"
                :precision="2"
                :disabled="form.status==0?false:true"
                :min="0"
              />
            </el-form-item>
            <el-form-item v-else label="燃油单价(元):" prop="fuelPrice">
              <label>{{ form.fuelPrice }}</label>
            </el-form-item>
          </el-col>
          <el-col v-if="form.totalFuel" :span="8">
            <el-form-item label="总油费(元):" prop="totalFuel">
              <label>{{ form.totalFuel }}</label>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item v-if="form.status==0" label="借款金额(元):" prop="borrowingAmount">
              <el-input-number
                v-model="form.borrowingAmount"
                controls-position="right"
                :precision="2"
                :disabled="form.status==0?false:true"
                :min="0"
              />
            </el-form-item>
            <el-form-item v-else label="借款金额(元):">
              <label>{{ form.borrowingAmount }}</label>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item v-if="form.status==0" label="借款时间:" prop="borrowingTime">
              <el-date-picker
                v-model="form.borrowingTime"
                value-format="yyyy-MM-dd"
                align="right"
                type="date"
                placeholder="选择日期"
                :picker-options="pickerOptions"
              />
            </el-form-item>
            <el-form-item v-else label="借款时间:" prop="borrowingTime">
              <label>{{ form.borrowingTime }}</label>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item v-if="form.status!==0" label="合计费用(元):" prop="borrowingTime">
              <label>{{ form.totalCost }}</label>
            </el-form-item>
          </el-col>

        </el-row>
        <el-form-item label="备注：" prop="remark">
          <el-input v-model="form.remark" class="col-6" type="textarea" :rows="4" :disabled="form.status==0?false:true" />
        </el-form-item>
        <el-row class="row-bg">
          <el-col :span="8">
            <el-form-item label="申请人：">
              <label>{{ form.creator }}</label>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="申请时间：">
              <label>{{ form.createTime }} </label>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="更新时间：">
              <label>{{ form.updateTime }} </label>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">直达车信息</el-divider>
        <el-row class="row-bg">
          <el-col :span="8">
            <el-form-item label="货品：">
              <label v-for="(item, index) in form.toOrderInfo.orderProductList" :key="index" style="display: block">{{ item.name + "-" + item.weight + "吨" }}</label>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发车时间：">
              <label>{{ form.toOrderInfo.orderProcessList[0].createTime }} </label>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row-bg">
          <el-col :span="8">
            <el-form-item label="发货地址：">
              <label>{{ form.toOrderInfo.startArea+" "+form.toOrderInfo.startAddress }} </label>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收货地址：">
              <label>{{ form.toOrderInfo.endArea+" "+form.toOrderInfo.endAddress }} </label>
            </el-form-item>
          </el-col>
        </el-row>

        <template v-if="form.returnOrderInfo != null">
          <el-divider content-position="left">回头车信息</el-divider>
          <el-row class="row-bg">
            <el-col :span="8">
              <el-form-item label="货品：">
                <label v-for="(item, index) in form.returnOrderInfo.orderProductList" :key="index" style="display: block">{{ item.name + "-" + item.weight + "吨" }}</label>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发车时间：">
                <label>{{ form.returnOrderInfo.orderProcessList[0].createTime }} </label>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="row-bg">
            <el-col :span="8">
              <el-form-item label="发货地址：">
                <label>{{ form.returnOrderInfo.startArea+" "+form.returnOrderInfo.startAddress }} </label>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="收货地址：">
                <label>{{ form.returnOrderInfo.endArea+" "+form.returnOrderInfo.endAddress }} </label>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <el-divider content-position="left">驾驶员信息</el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="驾驶员：" prop="name">
              <label>{{ form.driverVo.name }}</label>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系方式：" prop="phone">
              <label>{{ form.driverVo.phone }} </label>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="车牌号：" prop="carNo">
              <label>{{ form.driverVo.carNo }} </label>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="挂车车牌号：" prop="semitrailerNo">
              <label>{{ form.semitrailerNo }} </label>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <!-- 审核信息 -->
      <!-- <div v-if="form.status>1">
        <el-divider content-position="left">审核信息</el-divider>
        <el-form-item label="审核信息:" prop="sort">
          <label>{{ form.logisticsCheckMsg }} </label>
        </el-form-item>
      </div> -->
      <!-- 核对信息 -->
      <!-- <div v-if="form.status>2">
        <el-divider content-position="left">核对信息</el-divider>
        <el-form-item label="核定金额:" prop="sort">
          <label>{{ form.refundableFee }} 元</label>
        </el-form-item>
        <el-form-item label="补充说明:" prop="sort">
          <label>{{ form.financeCheckMsg }} </label>
        </el-form-item>
      </div> -->
      <!-- 结算信息 -->
      <!-- <div v-if="form.status>3">
        <el-divider content-position="left">结算信息</el-divider>
        <el-form-item label="结算凭证：" prop="remark">
          <el-image
            v-for="(item,index) in settleReceipts"
            :key="index"
            fit="contain"
            :src="item"
            :preview-src-list="settleReceipts"
          />
        </el-form-item>
      </div> -->

      <!-- 详情流程 -->
      <div v-if="form.id !=null" class="details">
        <el-tabs value="expensesDetailList" type="border-card">
          <el-tab-pane label="费用明细" name="expensesDetailList">
            <div class="bg" />
            <table cellspacing="0" cellpadding="0">
              <thead>
                <tr>
                  <th class="index">#</th>
                  <th class="tool" valign="middle">
                    <el-button class="btn" size="mini" icon="el-icon-plus" :disabled="form.status==0?false:true" @click="plus" />
                  </th>
                  <th>行驶类型</th>
                  <th>费用类型</th>
                  <th>费用名称</th>
                  <th>费用/元</th>
                  <!-- <th>凭据</th> -->
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in form.expensesDetailList " :key="index">
                  <td class="index">{{ index+1 }}</td>
                  <td class="tool">
                    <el-button size="small" class="btn" icon="el-icon-minus" :disabled="form.status==0?false:true" @click="minus(index)" />
                  </td>
                  <!-- 行使类型 -->
                  <td>
                    <el-form-item
                      :prop="'expensesDetailList.' + index + '.drivingType'"
                      :rules="page.rules.def"
                      label-width="0px"
                    >
                      <el-select v-model="item.drivingType" size="small" placeholder="请选择" :disabled="form.status==0?false:true">
                        <el-option
                          v-for="val in constants.exerciseType.values()"
                          :key="val.value"
                          :label="val.label"
                          :value="val.value"
                        />
                      </el-select>
                    </el-form-item>
                  </td>
                  <!-- 费用类型 -->
                  <td>
                    <el-form-item
                      :prop="'expensesDetailList.' + index + '.categoryId'"
                      :rules="page.rules.def"
                      label-width="0px"
                    >
                      <el-tooltip class="item" effect="dark" content="其他费用类型，需填写费用名称" placement="top">
                        <form-remote-select
                          v-model="item.categoryId"
                          :url="service.conf.api.get('wms').url+'/api/logistics/expenses-category/map'"
                          :disabled="form.status==0?false:true"
                          @change="(current)=>bindProduct(current,item,index)"
                        />
                      </el-tooltip>
                    </el-form-item>
                  </td>
                  <!-- 费用名称 -->
                  <td>
                    <el-input v-model="item.title" type="text" placeholder="费用名称" :disabled="item.isOther?false:true" />
                  </td>
                  <!-- 费用金额 -->
                  <td>
                    <el-form-item
                      :prop="'expensesDetailList.' + index + '.price'"
                      :rules="page.rules.def"
                      label-width="0px"
                    >
                      <el-input-number
                        v-model="item.price"
                        controls-position="right"
                        :precision="2"
                        :disabled="form.status==0?false:true"
                        :min="0"
                      />
                    </el-form-item>
                  </td>
                  <!-- <td>
                    <el-form-item
                      :prop="'expensesDetailList.' + index + '.evidence'"
                      label-width="0px"
                    >
                      <form-upload-image v-model="item.evidence" size="mini" :remote="upload.img" />
                    </el-form-item>
                  </td> -->
                </tr>
              </tbody>
            </table>
          </el-tab-pane>
          <el-tab-pane v-if="form.id!=null" label="操作日志" name="log">
            <logs v-model="form.id" :datalogs="form.expensesProcessList" />
          </el-tab-pane>
        </el-tabs>
      </div>
      <!-- model -->
      <div v-if="form.id!=null" class="action">
        <pur-paying ref="paying" v-model="form.id" :self="self" />
        <pur-canceling ref="canceling" v-model="form.id" :self="self" :url="audioUrl" />
        <financer-checking ref="FinancerChecking" v-model="form.id" :self="self" />
        <logistics-checking ref="logisticsChecking" v-model="form.id" :self="self" />
      </div>

    </el-form>
  </edit-layout>
</template>
<script>
import logs from './logs.vue'
import adminSupport from 'lola-admin-support-el'
import PurCanceling from './components/canceling.vue'
import PurPaying from './components/paying.vue'
import FinancerChecking from './components/FinancerChecking.vue'
import LogisticsChecking from './components/logisticsChecking.vue'
export default {
  name: 'CostEdit',
  components: { logs, PurCanceling, PurPaying, FinancerChecking, LogisticsChecking },
  mixins: [adminSupport.mixins.edit],
  data() {
    return {
      name: 'Cost',
      dialogImageUrl: '',
      dialogVisible: false,
      self: null,
      audioUrl: '',
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },

      settleReceipts: [] // 结算凭证
    }
  },
  watch: {
    'form': function() {
      const arr = this.form.expensesProcessList
      // console.log('监听form表单改变')
      // console.log(arr)
      if (!arr) return false
      arr.forEach(val => {
        if (val.flag === 1 && val.actionCode === 1) { // 提交

        } else if (val.flag === 1 && val.actionCode === 2) { // 审核
          this.form.logisticsCheckMsg = val.intro
        } else if (val.flag === 1 && val.actionCode === 3) { // 核算
          this.form.financeCheckMsg = val.intro
        } else if (val.flag === 1 && val.actionCode === 4) { // 结算
          this.settleReceipts = JSON.parse(val.credentials)
        }
      })
    }
    // 'form.returnOrderId': function(val) {
    //   console.log(val === undefined)
    //   if (val === 'undefined' && this.form.status === 0) {
    //     this.form.returnOrderInfo = null
    //   }
    // }
  },
  mounted() {
    this.page.tip = ''
    this.init() // 初始化
  },
  methods: {
    init() {
      const that = this
      that.page.tip = '请认真填写费用信息/里程信息等相关选项,创建后禁止修改!'
      that.self = this
      that.page.ids.push(this.$route.params.no) // 页面主参数赋值
      that.loadData() // 加载数据
    },
    appendForm() {
      this.orderStatus = this.$constants.costStatus.get(this.form.status)
      const roleIds = []
      if (this.form.roles != null) {
        this.form.roles.forEach(item => {
          roleIds.push(item.id)
        })
      }
      this.form.roleIds = roleIds
    },
    buildForm() {
      return true
    },
    // 添加明细
    plus() {
      this.form.expensesDetailList.push({ drivingType: null, categoryId: null, price: null, evidence: null, title: null })
      console.log(this.form.expensesDetailList)
    },
    // 删除明细
    minus(index) {
      this.form.expensesDetailList.splice(index, 1)
    },
    bindProduct(current, item, index) {
      console.log(current)
      console.log(item)
      console.log(index)
      if (current.name === '其他') { // 非严谨判断
        this.form.expensesDetailList[index].isOther = true
      } else {
        this.form.expensesDetailList[index].isOther = false
        this.form.expensesDetailList[index].title = current.name
      }
    },
    // 运输单选择切换
    toOrderNoChange(val) {
      console.log(val)
      this.form.toOrderNo = val.name
    },
    // 本次里程校验
    inputNowMileage(val) {
      console.log(val)
      console.log(this.form)
      if (val < this.form.preMileage) {
        this.form.nowMileage = ''
        this.$message.error('里程数有误，本次里程数不能低于上次里程数')
      }
    },
    // 获取回头车订单信息
    getReturnOrderMsg(id) {
      var that = this
      const url = that.$http.conf.api.get('wms').url + '/api/logistics/order/findReturnInfo/' + id
      that.$http.get(url, {}).then(function(rsp) {
        if (rsp.code !== 200) {
          that.$message.error(rsp.message)
          return
        }
        that.form.returnOrderInfo = rsp.data
      }).catch(function(err) {
        console.log(err)
      })
    },
    // 绑定回头运输单
    bindchaneReturnOrder(e) {
      console.log(e)
      if (e === undefined) {
        this.form.returnOrderInfo = null
      } else {
        this.form.returnOrderNo = e.name
        this.getReturnOrderMsg(e.code)
      }
    },
    // 重写按钮方法
    buildOtherBtn(item, btn) {
      switch (item.code) {
        case 'm5142': // 删除
          btn.disable = this.form.status !== 0 && this.form.id !== null
          btn.type = 'warning'
          break
        // case 'm5165': // 提交
        //   btn.disable = this.form.id !== null && this.form.status === 0
        //   btn.type = 'info'
        //   btn.opt = 'submit'
        //   break
        // case 'm51691': // 物流主管审核
        //   btn.disable = this.form.id !== null && this.form.status === 1
        //   btn.type = 'info'
        //   btn.opt = 'logisticsAudit'
        //   break
        // case 'm5166': // 财务审核
        //   btn.disable = this.form.id !== null && this.form.status === 2
        //   btn.type = 'warin'
        //   btn.opt = 'financeChecking'
        //   break
        case 'm5167': // 取消
          btn.disable = this.form.id !== null && this.form.status !== -1 && this.form.status < 1
          btn.type = 'danger'
          btn.opt = 'canceling'
          break
        case 'm5165': // 结算
          btn.disable = this.form.id !== null && this.form.status === 1
          btn.type = ''
          btn.opt = 'settlement'
          break
        case 'm5168': // 司机确认
          btn.disable = this.form.id !== null && this.form.status === 2
          btn.type = ''
          btn.opt = 'complete'
          break
        case 'm5166': // 驳回
          btn.disable = this.form.id !== null && this.form.status !== -1 && this.form.status > 0 && this.form.status < 2
          btn.type = 'warning'
          btn.opt = 'rejected'
          break
      }
    },
    // submit() { // 提交申请
    //   console.log()
    //   const that = this
    //   const url = that.$http.conf.api.get('wms').url + '/api/logistics/expenses-info/submit'
    //   const params = { expensesId: this.form.id }
    //   this.$confirm('确认提交物流主管审核?', '提示', {
    //     type: 'warning'
    //   }).then(() => {
    //     that.$http.post(url, params).then(function(rsp) {
    //       if (rsp.code === 200) {
    //         that.$message.success('操作成功!')
    //         that.form.status = 1
    //         that.loadData()
    //       } else {
    //         that.$message.error(rsp.message)
    //       }
    //     })
    //   })
    // },
    // 物流主管审核
    // logisticsAudit() {
    //   this.$refs.logisticsChecking.show()
    // },
    // financeChecking() { // 财务审核
    //   this.$refs.FinancerChecking.show()
    // },
    rejected() { // 订单驳回
      this.$refs.canceling.show('rejected')
    },
    canceling() { // 取消订单
      this.$refs.canceling.show('canceling')
    },
    settlement() { // 财务结算
      this.$refs.paying.show(this.form.totalFuel + this.form.totalCost)
      // const that = this
      // const url = that.$http.conf.api.get('wms').url + '/api/logistics/expenses-info/financeAudit'
      // const params = { expensesId: this.form.id }
      // this.$confirm('确认结算?', '提示', {
      //   type: 'warning'
      // }).then(() => {
      //   that.$http.post(url, params).then(function(rsp) {
      //     if (rsp.code === 200) {
      //       that.$message.success('操作成功!')
      //       setTimeout(() => {
      //         location.reload()
      //         that.loadData()
      //       }, 1500)
      //     } else {
      //       that.$message.error(rsp.message)
      //     }
      //   })
      // })
    },
    complete() { // 司机确认
      const that = this
      const url = that.$http.conf.api.get('wms').url + '/api/logistics/expenses-info/complete'
      const params = { expensesId: this.form.id }
      this.$confirm('是否确认收款?', '提示', {
        type: 'success'
      }).then(() => {
        that.$http.post(url, params).then(function(rsp) {
          if (rsp.code === 200) {
            that.$message.success('操作成功!')
            setTimeout(() => {
              location.reload()
              that.loadData()
            }, 1500)
          } else {
            that.$message.error(rsp.message)
          }
        })
      })
    }

  }
}
</script>
<style >

</style>
